package com.mixsmart.core.search.filter;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.util.HashMap;

import com.mixsmart.utils.StringUtils;

/**
 * 转换过滤对象的抽象类
 * @author lmq
 * 
 */
public abstract class AbstractConverSearchFilter implements IConvertSearchFilter {

	protected SearchFilter searchParam;
	
	protected HashMap<String, Object> params = null;

	/**
	 * 处理搜索参数
	 * @param searchParam 搜索对象
	 */
	public AbstractConverSearchFilter(SearchFilter searchParam) {
		this.searchParam = searchParam;
		if(null != this.searchParam) {
			params = new HashMap<String, Object>();
			convert(this.searchParam.getClass());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void convert(Class<? extends SearchFilter> clazz) {
		if(null != clazz) {
			Field[] fields = clazz.getDeclaredFields();
			if(null != fields && fields.length > 0) {
				try {
					for(Field field : fields) {
						if(field.getModifiers() == Modifier.PRIVATE || field.getModifiers() == Modifier.PROTECTED || field.getModifiers() == Modifier.PUBLIC) {
							String fieldName = field.getName();
							String methodName = "get"+ StringUtils.firstToUppercase(fieldName);
							Method method = clazz.getDeclaredMethod(methodName);
							if(null != method) {
								Object value = method.invoke(searchParam);
								if(null != value && StringUtils.isNotEmpty(value.toString())) {
									if(null != value && value instanceof String &&  value.toString().startsWith("%")) {
										params.put(fieldName, URLDecoder.decode(value.toString(), "UTF-8"));
									} else if(value.getClass().isArray()){
										Object[] values = (Object[])value;
										if(values.length > 0 ) {
											params.put(fieldName, value);
										}
									} else {
										params.put(fieldName, value);
									}
								}
							}
							method = null;
						}
					}
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Class<?> superClazz = clazz.getSuperclass();
			if (null != superClazz) {
				convert((Class<? extends SearchFilter>) superClazz);
			}
		}
	}
}
